 package cn.wit.luohui.day10;

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import org.junit.Test;

public class DemoRandomAccessFile {
	@Test
	public void test() {
		//String source="test.java";
		String source="C:\\Users\\luohui\\Desktop\\1530764039764.jpeg";//导入文件
		String target="C:\\Users\\luohui\\Desktop\\1530764039765.jpeg";//目标文件
	
		System.out.println(new File(source).exists());//验证文件是否存在，true表存在
		copy(source,target);
	}
	
	public static void copy(String source,String target) {
		try(
				FileInputStream fi=new FileInputStream(source);
		FileOutputStream fo=new FileOutputStream(target);
	){
	byte[] bytes=new byte[1024];
	int count=0;
	
	//文件大小
	File f=new File(source);
	long size=f.length();
	
	//取到一个随机的位置
	long ran=(long)(Math.random()*size);
	
	long sum=0;
	while((count=fi.read(bytes))!=-1) {
		//复制到随机位置时，中断
		sum+=count;
		if(sum>=ran)break;
		
		fo.write(bytes, 0, count);
	}
	System.out.println("文件大小："+size);
	System.out.println("复制停止："+ran);
	
} catch (IOException e) {
	e.printStackTrace();
}
}
	
@Test//恢复图片
public void copyRemain() {
	String source="C:\\Users\\luohui\\Desktop\\1530764039764.jpeg";
	String target="C:\\Users\\luohui\\Desktop\\1530764039765.jpeg";
	
	File targetFile=new File(target);
	
	try (
			RandomAccessFile raf=new RandomAccessFile(source,"r");//以只读模式打开
			FileOutputStream fo=new FileOutputStream(target,true);//往后追加文件
		){
		long filePointer=raf.getFilePointer();//获取文件指针的位置
		raf.seek(1024);//移动文件指针
		
		long size=targetFile.length();//已复制了多少字节
		raf.seek(size);
		
		byte[] bytes=new byte[1024];
		int count=0;
		while((count=raf.read(bytes))!=-1){//在=-1时终止
			fo.write(bytes, 0, count);
			System.out.println(count);
		}
		System.out.println(Arrays.toString(bytes));
		
	}catch (IOException e) {
		
		e.printStackTrace();
	}
}
	
}
